package zzxkj.blog.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import zzxkj.blog.WorkingException.NotFoundException;
import zzxkj.blog.dto.DetailedBlog;
import zzxkj.blog.pojo.Comment;
import zzxkj.blog.pojo.User;
import zzxkj.blog.service.BlogService;
import zzxkj.blog.service.CommentService;
import zzxkj.blog.shiro.AccountProfile;

import javax.servlet.http.HttpSession;

/**
 * 评论相关
 * @author zzxkj
 */
@Slf4j
@Controller
public class CommentController {

    final
    CommentService commentService;
    final
    BlogService blogService;

    /**
     * 配置文件中定义写死的头像
     */
    @Value("${comment.avatar}")
    private String avatar;

    public CommentController(CommentService commentService, BlogService blogService) {
        this.commentService = commentService;
        this.blogService = blogService;
    }

    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model) {
        model.addAttribute("comments", commentService.listFinCommentByBlogId(blogId));
        return "blog :: commentList";
    }


    @PostMapping("/comments")
    public String post(Comment comment) {
        AccountProfile profile = (AccountProfile) SecurityUtils.getSubject().getPrincipal();
        if(profile == null){
            throw new NotFoundException("还未登录，禁止评论！！！");
        }
        comment.setAvatar(profile.getAvatar());
        comment.setAdminComment(profile.getType());
        comment.setEmail(profile.getEmail());
        comment.setNickname(profile.getNickname());
        Long blogId = comment.getBlog().getId();
        commentService.saveComment(comment);
        return "redirect:/comments/" + blogId;
    }

}
